//
//  TransverseSelectView.m
//  YHBulter
//
//  Created by Guava on 16/2/18.
//  Copyright © 2016年 Guava. All rights reserved.
//

#import "TransverseSelectView.h"

#define screenW [[UIScreen mainScreen] bounds].size.width //屏幕宽度

@interface TransverseSelectView()
/** 设置角标 */
@property (nonatomic, strong, readwrite) NSMutableArray<NSNumber *> *badges;

@end

@implementation TransverseSelectView

- (void)awakeFromNib {
    [super awakeFromNib];
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouch:)];
    [self addGestureRecognizer:gesture];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    for(int i = 0; i < [self.titleArray count]; i++) {
        [self drawTitleAndUnderlineWithTitle:self.titleArray[i]
                                hasUnderline:(i == self.selectedLocation)
                                hasSeparator:(i != [self.titleArray count]-1)
                                        sort:i];
    }
}
- (void)drawTitleAndUnderlineWithTitle:(NSString *)title
                          hasUnderline:(BOOL)hasUnderline // 也可用于判断是否被选中
                          hasSeparator:(BOOL)hasSeparator
                                  sort:(NSInteger)rank {
    /** 绘制文字 */
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSDictionary *attributeDictionary =@{
                                         NSFontAttributeName:[UIFont systemFontOfSize:[self automFontSize]],
                                         NSParagraphStyleAttributeName:paragraphStyle,
                                         NSForegroundColorAttributeName:hasUnderline ? self.selectedColor :self.unselectedColor
                                         };
    NSAttributedString *test = [[NSAttributedString alloc] initWithString:title
                                                               attributes:attributeDictionary];
    //获取绘制区域中心点
    NSInteger selectedCount = [self.titleArray count];
    CGFloat lengthOfEachSelectedSpace = self.frame.size.width /selectedCount;
    CGFloat horizontalStartLocation = lengthOfEachSelectedSpace *rank;
    CGFloat horizontalEndLocation = lengthOfEachSelectedSpace *(rank +1);
    CGFloat horizontalCenterLocation = (horizontalStartLocation + horizontalEndLocation) /2;
    //获取绘制区域大小
    CGRect titleRect = [title boundingRectWithSize:CGSizeMake([self scaleWidthOfTitleDrawSpace], [self scaleHeightOfTitleDrawSpace])
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:attributeDictionary
                                           context:nil];
    CGFloat drawSpaceWidth = titleRect.size.width;
    CGFloat drawSpaceHeight = titleRect.size.height;
    
    CGRect drawRect = CGRectMake(horizontalCenterLocation - drawSpaceWidth/2.0, self.frame.size.height/2.0 - drawSpaceHeight/2.0, drawSpaceWidth, drawSpaceHeight);
    [test drawInRect:drawRect];
    
//  绘制分割线
    if(hasSeparator && !self.hiddenSeparator) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextMoveToPoint(context, horizontalEndLocation, (self.frame.size.height - [self scaleSeparatorHeight])/2);
        CGContextAddLineToPoint(context,horizontalEndLocation,(self.frame.size.height - [self scaleSeparatorHeight])/2 +[self scaleSeparatorHeight]);
        CGContextSetRGBStrokeColor(context, 228.0/255, 228.0/255, 228.0/255, 1);
        CGContextSetLineWidth(context, 1);
        CGContextStrokePath(context);
    }
    
//  绘制下划线
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextMoveToPoint(context, horizontalStartLocation, self.frame.size.height);
        CGContextAddLineToPoint(context, horizontalEndLocation, self.frame.size.height);
        if(hasUnderline) {
            CGFloat r, g, b,alpha;
            [self.selectedColor getRed:&r green:&g blue:&b alpha:&alpha];
            CGContextSetRGBStrokeColor(context, r, g, b, alpha);
            CGContextSetLineWidth(context, 2);
        }
        else {
            CGContextSetRGBStrokeColor(context, 228.0/255, 228.0/255, 228.0/255, 1);
            CGContextSetLineWidth(context, 1);
        }
        CGContextStrokePath(context);
    }
//    绘制角标
    if([self.badges[rank] integerValue] != 0) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGPoint centerOfBadge = CGPointMake(drawRect.origin.x + drawRect.size.width + [self scaleBadgeRadius], drawRect.origin.y);
        CGContextAddArc(context, centerOfBadge.x, centerOfBadge.y, [self scaleBadgeRadius], 0, 2* M_PI, 0);
        CGFloat red, green, blue, alpha;
        [self.badgeColor getRed:&red green:&green blue:&blue alpha:&alpha];
        CGContextSetRGBFillColor(context, red, green, blue, alpha);
        CGContextFillPath(context);
        NSDictionary *badgeAttributeDic = @{
                                             NSFontAttributeName:[UIFont systemFontOfSize:[self scaleBadgeFont]],
                                             NSParagraphStyleAttributeName:paragraphStyle,
                                             NSForegroundColorAttributeName:[UIColor whiteColor]
                                            };
        NSAttributedString *attributeString = [[NSAttributedString alloc]
                                               initWithString:[NSString stringWithFormat:@"%ld",[self.badges[rank] integerValue]]
                                               attributes:badgeAttributeDic];
        CGRect rect = CGRectMake(centerOfBadge.x - [self scaleBadgeRadius], centerOfBadge.y - [self scaleBadgeRadius], 2*[self scaleBadgeRadius], 2*[self scaleBadgeRadius]);
        [attributeString drawInRect:rect];
        
    }
    
    
}

#pragma mark - 颜色设置
/** 设置选中时默认颜色 */
#define SELECTED_DEFAULT_COLOR [UIColor colorWithRed:88.0/255 green:188.0/255 blue:231.0/255 alpha:1]
/** 设置未选中时默认颜色 */
#define UNSELECTED_DEFAULT_COLOR [UIColor colorWithRed:102.0/255 green:102.0/255 blue:102.0/255 alpha:1]
/** 分割线默认颜色 */
#define SEPARATOR_COLOR [UIColor colorWithRed:186.0/255 green:186.0/255 blue:186.0/255 alpha:1]
- (UIColor *)selectedColor {
    if (!_selectedColor) {
        return SELECTED_DEFAULT_COLOR;
    }
    else  {
      return _selectedColor;
    }
}
- (UIColor *)unselectedColor {
    if(!_unselectedColor) {
        return UNSELECTED_DEFAULT_COLOR;
    }
    else {
        return _unselectedColor;
    }
}

#pragma mark - 按比例数据
/** 视图原始高度值 */
static CGFloat NATURAL_VIEW_HEIGHT = 35.0;
/** 视图原始字体大小 */
static CGFloat NATURAL_FONT_SIZE = 16.0;
/** badge半径 */
static CGFloat BADGE_RADIUS = 6.0;
/** badge字体 */
static CGFloat BADGE_FONT = 10;
/** 视图比例因子 */
- (CGFloat)scaleFactor {
    return self.frame.size.height / NATURAL_VIEW_HEIGHT;
}
/** 分割线高度 */
- (CGFloat)scaleSeparatorHeight {
    return self.frame.size.height / 2.0;
}
/** 字体大小 */
- (UIFont *)scaleFont {
    return [UIFont systemFontOfSize: NATURAL_FONT_SIZE * [self scaleFactor] ];
}
//设置文字绘制区域的大小
/** 区域高度 */
static CGFloat NATURAL_HEIGHT_OF_TITLE_SPACE = 20.0;
/** 区域长度 */
static CGFloat NATURAL_WIDTH_OF_TITLE_SPACE = 70.0;
/** 按比例的绘制区域高度 */
- (CGFloat)scaleHeightOfTitleDrawSpace {
    return NATURAL_HEIGHT_OF_TITLE_SPACE * [self scaleFactor];
}
/** 按比例的绘制区域宽度 */
- (CGFloat)scaleWidthOfTitleDrawSpace {
    return NATURAL_WIDTH_OF_TITLE_SPACE * [self scaleFactor];
}

//badge绘制
/** 按比例的badge字体 */
- (CGFloat)scaleBadgeFont {
    return [self scaleFactor] *BADGE_FONT;
}
/** 按比例的badge半径 */
- (CGFloat)scaleBadgeRadius {
    return [self scaleFactor] *BADGE_RADIUS;
}

#pragma mark - property override
- (void)setSelectedLocation:(NSInteger)selectedLocation {
    _selectedLocation = selectedLocation;
    [self setNeedsDisplay];
}
- (void)setTitleArray:(NSArray<NSString *> *)titleArray {
    _titleArray = titleArray;
    //设置titleArray之后会清除角标。
    self.badges = nil;
    [self setNeedsDisplay];
}
- (NSMutableArray<NSNumber *> *)badges {
    if(!_badges) {
        if([self.titleArray count] == 0) {
            NSLog(@"%@ error! should set titleArray!", [self class]);
            return nil;
        }
        _badges = [[NSMutableArray alloc] init];
        for(int i = 0; i < [self.titleArray count]; i++) {
            [_badges addObject:@(0)];
        }
    }
    return _badges;
}
- (UIColor *)badgeColor {
    if(!_badgeColor) {
        _badgeColor = [UIColor redColor];
    }
    return _badgeColor;
}
#pragma mark - 点击事件监听
- (void)tapTouch:(UITapGestureRecognizer *)recognizer {
    if(recognizer.state == UIGestureRecognizerStateEnded) {
        //获取下一个选择的选项是哪个
        NSInteger nextLocation = [self judgeTapSpace:[recognizer locationInView:self].x];
        //如果选择的选项改变了。调用回调函数。  或者设置了重复选择时回调
        if((self.selectAction != nil) || self.callbackWithRepeatSelect){
            self.selectAction(nextLocation);
        }
        self.selectedLocation = nextLocation;
    }
}
- (NSInteger)judgeTapSpace:(CGFloat)horizontalLocation {
    return (NSInteger) (horizontalLocation /(self.frame.size.width / [self.titleArray count]));
}

#pragma mark - 公开方法
- (void)setBadgeNumber:(NSInteger)badgeNumber location:(NSInteger)location {
    [self.badges replaceObjectAtIndex:location withObject:@(badgeNumber)];
    [self setNeedsDisplay];
}
#pragma mark - 自适应文字大小
- (CGFloat)automFontSize
{
    if ([self.titleArray count]>0) {
        float titleW = screenW / [self.titleArray count];
        int i = 0;
        float maxLength = [self.titleArray[0] length];
        for ( ;i < [self.titleArray count]; i++) {
            if (maxLength < [self.titleArray[i] length]) {
                maxLength = [self.titleArray[i] length];
            }
        };
        return (titleW / (maxLength + 2))> NATURAL_FONT_SIZE ? NATURAL_FONT_SIZE:(titleW / (maxLength + 2));
    }else{
        return NATURAL_FONT_SIZE;
    }
}
@end












